import cfg from "../../config";
import {getView} from "../../util/api";
import * as ajax from "../../lib/kajax";
import {formatDate, backPage, tabSwitch, message} from "../../util/aid";
import {findOrderDelData, refundsOrder, changeSignOrder, getTicketnosStr, concelOrder, payorderFun} from '../common';
import {tripsObj, orderStatus, orderCls} from "../../util/const.config";
import Dialog from "../../lib/kdialog";
const dialog = new Dialog();

const $ = require('../../lib/kdom');
let _view = require('raw-loader!./order.html');
let orderData = null;
let _url = '/train/order';
let testdata = null;
export default class {
    path = '/train/order$';
    hash = '/train/order';
    title = '订单';

    constructor(opt) {
        opt = opt || {};
        this.path = opt.path || this.path;
        this.hash = opt.hash || this.hash;
        this.title = opt.title || this.title;
    }

    // 输出视图
    view(cb) {
        if (!_view) {
            // 静态资源浏览器有缓存,增加时标,强制刷新!
            getView(`${cfg.train.view.order}?t=${(+new Date())}`, '', (rs) => {
                _view = rs;
                cb(null, _view);
            });
        } else
            cb(null, _view);
    }

    // 在已经加载的视图上操作
    bind(dv, params) {
        let _status = null;

        // 加载动画
        dialog.loading();

        // tab
        // orderTabFun();

        // OrderList
        loadOrderListFun();

        // tab 切换
        tabSwitch($.qus('#orderTabBox .tab-link'), (that) => {
            dialog.loading();
            _status = that.getAttribute('data-val');
            // console.log(_status);
            loadOrderListFun(_status);
        });

        // backPage
        backPage('#pg-train-order', 'backPage', () => {
            $.router.go('/train/user', '', true);
        });
    }

    /*bind*/
}

/*function orderTabFun() {
 let rc = `<a href="javascript:;" class="tab-link button" data-val="0">待付款</a><a href="javascript:;" class="tab-link button" data-val="1">处理中</a><a href="javascript:;" class="tab-link button" data-val="2">已完成</a><a href="javascript:;" class="tab-link button active" data-val="">全部</a>`;
 $.html(orderTabBox, rc)
 }*/

function loadOrderListFun(currStatus) {
    ajax.get(`${cfg.train.host}${cfg.train.orderList}`, '', (rs) => {
        if (rs) {
            careteOrderList(rs, currStatus);
        } else {
            message('#orderAllList', '亲！您暂时还没有获取到订单的相关信息哦，请重新查询哦！');
        }
    });
}

function careteOrderList(rs, currStatus) {
    rs = rs instanceof Object ? rs : JSON.parse(rs);
    //缓存到全局
    orderData = rs;
    // console.log('排序前：', rs);

    let orderInfo = rs.orderInfo;
    orderInfo.sort((x, y) => {// 排序
        return (x['sdate'] > y['sdate']) ? 1 : -1;
    });

    console.log('排序后：', orderInfo);

    // console.log('order列表：', orderData);

    let rc = '';
    for (let j = 0, passengerInfo = rs.passengerInfo; j < orderInfo.length; j++) {
        if (!currStatus) {
            rc += textFragment(orderInfo[j], orderInfo[j].orderID);
            $.html(orderAllList, rc);
        } else {
            if (currStatus.indexOf(',') > -1) {
                currStatus = currStatus.split(',');
                for (let i = 0; i < currStatus.length; i++) {
                    if (currStatus[i] && orderInfo[j].status == currStatus[i]) {
                        rc += textFragment(orderInfo[j], orderInfo[j].orderID);
                        $.html(orderAllList, rc);
                    } else {
                        $.html(orderAllList, '');
                        message('#orderAllList', '亲！您暂时还没有获取到订单的相关信息哦，请重新查询哦！');
                    }
                }
            } else if (currStatus && orderInfo[j].status == currStatus) {
                if (currStatus == 2) {
                    if (new Date(orderInfo[j].sdate) > new Date()) {
                        rc += textFragment(orderInfo[j], orderInfo[j].orderID);
                    }
                } else {
                    rc += textFragment(orderInfo[j], orderInfo[j].orderID);
                }
                $.html(orderAllList, rc);
            }

            if (!rc) {
                $.html(orderAllList, '');
                message('#orderAllList', '亲！您暂时还没有获取到订单的相关信息哦，请重新查询哦！');
            }
        }
    }
    dialog.close();
}

// 片段
function textFragment(obj, idx) {
    let _status = obj.status;

    // console.log('我是状态：');
    // console.log(obj);

    let temp = '';
    let concel = '';
    let changeSign = '';
    let orderPayMent = '';
    let refunds = '';
    let Tickets = '';
    let ticketnos = [];
    let curST = []; //当前显示的状态
    let outOrderID = obj.outOrderID;
    let orderRCAll = obj.orderRCAll;
    Tickets = orderRCAll ? JSON.parse(orderRCAll) : '';
    Tickets = Tickets.data ? Tickets.data.Tickets : '';

    if (new Date(obj.sdate) > new Date()) {
        if (_status == 1 || _status == 2) {
            concel = `<span class="button button-dark" onclick="concelOrderFun('${outOrderID}')">取消</span>`;
            if (_status == 2) {
                orderPayMent = `&nbsp;&nbsp;<span class="button button-danger" onclick="orderPayMentFun('${obj.orderID}')">支付</span>`;
            }
        }

        if (_status == 7) {
            changeSign = `&nbsp;&nbsp;<span class="button" onclick="changeSignOrderFun('${idx}')">改签</span>`;
        }

        if (_status == 7) {
            if (Tickets) {
                ticketnos = getTicketnosStr(Tickets);
            }
            // console.log('ticketnos', ticketnos);
            refunds = `&nbsp;&nbsp;<span class="button button-danger" onclick="refundsOrderFun('${outOrderID}','${ticketnos.join(',')}')">退票</span>`;
        }
    }
    if (new Date(obj.sdate) > new Date()) {
        curST = `<span class="${orderCls[obj.status]}">${orderStatus[obj.status]}</span>`;
    } else {
        if (_status == 1 || _status == 2) {
            curST = `<span class="${orderCls['9']}">${orderStatus['9']}</span>`;
        } else {
            curST = `<span class="${orderCls[obj.status]}">${orderStatus[obj.status]}</span>`;
        }
    }
    console.log(curST);
    if (concel || changeSign || refunds) {
        temp = `<div class="flex-block" data-order="">
              <span></span>
              <span class="flex-block">
                  ${concel}
                  ${changeSign}
                  ${refunds}
                  ${orderPayMent}
              </span>
         </div>`;
    }

    return `<li>
            <div class="item-link item-content" onclick="showOrderDetail(${idx})">
                <div class="item-inner">
                    <div class="item-title-row">
                        <div class="item-title">${obj.fromstation}&nbsp;-&nbsp;${obj.tostation}</div>
                        <div class="item-after">${curST}</div>
                    </div>
                    <div class="item-subtitle">
                        <div class="text-disabled">
                            <p>${obj.traincode} ${tripsObj[obj.traincode.substring(0, 1)]}</p>
                            <p>出发时间：${formatDate('yyyy-MM-dd hh:mm', new Date(obj.sdate))}</p>
                        </div>
                        <div class="text-danger">
                            <span class="f06">￥</span><b>${obj.totalprice}</b>
                        </div>
                    </div>
                </div>
            </div>
            ${temp}
        </li>`;
}

window.showOrderDetail = (idx) => {
    let rs = findOrderDelData(orderData, idx);
    // console.log(rs);
    $.router.go('/train/order-detail', {orderData: rs, url: _url}, true);
};

window.concelOrderFun = (OrderNumber) => {
    concelOrder(OrderNumber);
};

window.refundsOrderFun = (OrderNumber, ticketnos) => {
    refundsOrder(OrderNumber, ticketnos);
};

window.changeSignOrderFun = (idx) => {
    let rs = findOrderDelData(orderData, idx);
    changeSignOrder(rs.orderInfo);
};
window.orderPayMentFun = (idx) => {
    let rs = findOrderDelData(orderData, idx);
    rs = JSON.parse(rs.orderInfo.orderRCAll);
    rs = rs.data;
    payorderFun(rs);
};
